const mongoose = require('mongoose');

mongoose.connect(process.env.MONGODB_PATH);

mongoose.Promise = require('bluebird');

const userSchema = new mongoose.Schema({
    username: String,
    password: String
});

const snippetSchema = new mongoose.Schema({
    author: String,
    title: String,
    desc: String,
    code: String,
    create_time: Date,
    modified_time: Date,
    mode: String
});

const user = mongoose.model('user', userSchema);
const snippet = mongoose.model('snippet', snippetSchema);

let _pack = {};

_pack.userValidation = function (username, password) {
    return user.findOne({
        username: username,
        password: password
    }).exec();
};

_pack.isAuthed = function (req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    res.redirect('/login');
}

_pack.submitSnippet = function (data) {
    if (data.id !== '') {
        return snippet.update({
            _id: data.id
        }, data, {
            upsert: false
        }).exec();
    } else {
        let sn = new snippet(data);
        return sn.save();
    }
}

_pack.getAllSnippets = function (uid) {
    return snippet.find({
        author: uid
    }).exec();
}

_pack.getSnippet = function (id) {
    return snippet.findOne({
        _id: id
    }).exec();
}

_pack.removeSnippet = function (id) {
    return snippet.findByIdAndRemove(id).exec();
}

module.exports = _pack;